﻿/**
 * 箱子类的构造方法。
 * @param back      背后对象
 * @param drawer    绘图者
 * @param gameBoard 游戏区域
 * @param type      类型
 * @param x, y      左上角坐标
 * @return 箱子
 */
function Box(back, drawer, gameBoard, type, x, y) {
    const baseGameObject = new BaseGameObject(drawer, gameBoard, type, x, y)

    // 初始化数据
    baseGameObject.mBack = back                             // 背后对象
    baseGameObject.mCurrentImage = baseGameObject.mImage    // 当前图片
    baseGameObject.mImage2 = new Image()                    // 图片2
    baseGameObject.mImage2.src = Const.IMAGE_FILE_PATH + (type * 10 + 1) + Const.IMAGE_FILE_EXT

    // 初始化方法
    baseGameObject.move = Box_Move

    return baseGameObject
}

/**
 * 箱子移动。
 * @param baseGameObject    基本游戏物体
 * @param direction         方向
 * @param moveResult        移动结果
 * @return 被推动的箱子
 */
function Box_Move(baseGameObject, direction, moveResult) {
    var leftFromDest = false                                    // 是否离开目的地
    var destX = baseGameObject.mX, destY = baseGameObject.mY    // 新位置的坐标

    if (direction == Const.KEY_LEFT) {
        destX--
    } else if (direction == Const.KEY_RIGHT) {
        destX++
    } else if (direction == Const.KEY_UP) {
        destY--
    } else if (direction == Const.KEY_DOWN) {
        destY++
    }

    // 如果旁边是墙或箱子，则直接返回
    if (gBaseGameObjects[destY][destX].mType == GameObjectType.WALL ||
        gBaseGameObjects[destY][destX].mType == GameObjectType.BOX) {
        moveResult.result = _MoveResult.NO_MOVE
        return null
    }

    // 设置移动结果
    if (moveResult.result < _MoveResult.NORMAL_MOVED) {
        moveResult.result = _MoveResult.NORMAL_MOVED
    }

    // 判断是否要离开目的地
    if (baseGameObject.mType == GameObjectType.BOX && baseGameObject.mBack.mType == GameObjectType.DESTINATION) {
        leftFromDest = true
        moveResult.result = _MoveResult.LEFT_FROM_DEST
        baseGameObject.mCurrentImage = baseGameObject.mImage
    }

    // 用背后对象擦除自己
    baseGameObject.mBack.draw()
    gBaseGameObjects[baseGameObject.mY][baseGameObject.mX] = baseGameObject.mBack

    // 计算新位置
    baseGameObject.mX = destX
    baseGameObject.mY = destY

    // 设置新的背后对象
    baseGameObject.mBack = gBaseGameObjects[baseGameObject.mY][baseGameObject.mX]

    // 判断是否到达目的地
    if (baseGameObject.mType == GameObjectType.BOX && baseGameObject.mBack.mType == GameObjectType.DESTINATION) {
        if (leftFromDest) {
            moveResult.result = _MoveResult.NORMAL_MOVED
        } else {
            moveResult.result = _MoveResult.ARRIVED_ON_DEST
        }
        baseGameObject.mCurrentImage = baseGameObject.mImage2
    }

    // 重绘自己
    baseGameObject.mDrawer.drawImage(baseGameObject.mCurrentImage, baseGameObject.mX * Const.GRID_SIZE, baseGameObject.mY * Const.GRID_SIZE)

    // 将自己保存到数组中
    gBaseGameObjects[baseGameObject.mY][baseGameObject.mX] = baseGameObject

    return baseGameObject
}
